
var app = getApp();
var f = require('../../utils/files.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading_stat:1  //是否显示系统维护加载框
  },


  /**
   * 生命周期函数--监听页面加载
   */


  onLoad: function (options) {
    var t = this;
    t.GetStatusSet(app, f, function (StatusSet_stat) {  //加载状态集合
      if (StatusSet_stat != 'ok') {
        app.ViewError('10004 get StatusSet from upyun and local file is all fail ', 161);
        app.JumpError(10004);
      }else{
        var OpenCityStat = false;
        var DomainListStat = false;
        var GoodsTypeStat = false;

        //检测并加载开通城市
        t.CheckFieldStatusFail(f, app, 1, function (city_stat) {
          if (city_stat == 'ok') {  //数据有效,则读取到globalData
            if (app.globalData.LoadingConsole) console.log('OpenCity_file');
            f.Reads(app.globalData.OpenCity_path,function (OpenCityRes){
              if (/^{.*}$/.test(OpenCityRes)){
                app.globalData.OpenCityObj = JSON.parse(OpenCityRes);
              }else{
                app.ViewError('10009 the OpenCity data is error from local file', 161);
                app.JumpError(10009);
              }
            });
          }else{
            t.GetOpenCity(app, f, function (city_stat) {  //重新加载
              if (city_stat == 'ok') {
                //有更新时同时也删除当前选择城市缓存
                f.DelFile(app.globalData.CurrentCity_path,'',function(){}); 
              }
            })
          }
        });
        
        //检测并加载域名列表
        t.CheckFieldStatusFail(f, app, 2, function (res) {  //检测
          if (res == 'ok') {
            if (app.globalData.LoadingConsole) {
              console.log('DomainList_file');
            }
            f.Reads(app.globalData.DomainList_path,function(DomainListRes){
              if (/^\["http:.*\]$/.test(DomainListRes)) {
                app.globalData.DomainListObj = JSON.parse(DomainListRes);
              } else {
                app.ViewError('10016 DomainList data format is error from local file', 273);
                app.JumpError(10016);
              }
            });
          } else {
            t.GetDomainList(app, f, function (s1) {
              //重新加载域名列表
            })
          }
        });


        //检测并加载商品类别
        t.CheckFieldStatusFail(f, app, 3, function (res) {  //检测
          if (res == 'ok') {
            if (app.globalData.LoadingConsole) {
              console.log('GoodsType_file');
            }
            f.Reads(app.globalData.GoodsType_path,function (GoodsTypeRes) {
              if (/^{"g1":.*}$/.test(GoodsTypeRes)) {
                app.globalData.GoodsTypeObj = JSON.parse(GoodsTypeRes);
              } else {
                app.ViewError('10022 GoodsType data format is error from local file', 273);
                app.JumpError(10022);
              }
            });
          } else {
            t.GetGoodsType(app, f, function (s1) {
              //加载upyun 商品类别
            })
          }
        });


        var OpenCity_load = false;
        var DomainList_load = false;
        var GoodsType_load = false;
        var num = 0;
        var val = 50;   //定时器间隔 50 毫秒
        var intver_expire = 2000;  //超时时长
        var intver = setInterval(function(){
          num += val;
          if (app.globalData.OpenCityObj && app.globalData.OpenCityObj.province) {
           // app.C(app.globalData.OpenCityObj);
            OpenCity_load = true;
          }
          if (app.globalData.DomainListObj && app.globalData.DomainListObj.length > 0) {
            //app.C(app.globalData.DomainListObj);
            DomainList_load = true;
          }
          if (app.globalData.GoodsTypeObj && app.globalData.GoodsTypeObj.g1.length > 0) {
            //app.C(app.globalData.GoodsTypeObj);
            GoodsType_load = true;
          }
          

          if (OpenCity_load && DomainList_load && GoodsType_load){
            clearInterval(intver);
            if (app.globalData.LoadingConsole) {  
              app.C('四项基本数据加载完成，准备跳转页面');
              app.C(app.globalData.GoodsTypeObj);
              app.C(app.globalData.DomainListObj);
              app.C(app.globalData.OpenCityObj);
            }
            f.Reads(app.globalData.CurrentCity_path,function (CurrentCityRes) {
              if (/^{"id":.*}$/.test(CurrentCityRes)) {
                app.globalData.CurrentCityObj = JSON.parse(CurrentCityRes);
                wx.switchTab({
                  url: '../index/index',
                })
              } else {  //没有选择城市信息，则跳转到城市切换面
                wx.redirectTo({
                  url:'../city/city',
                });
              }
            });
          }
        
          if (num > intver_expire) {
            clearInterval(intver);
            if (!OpenCity_load) {
              app.ViewError('10025 OpenCity load is fail ', 161);
              app.JumpError(10025);
            }
            if (!DomainList_load) {
              app.ViewError('10024 DomainList load is fail ', 161);
              app.JumpError(10024);
            }
            if (!GoodsType_load) {
              app.ViewError('10023 GoodsType load is fail ', 161);
              app.JumpError(10023);
            }
          }
        },val);
      }
    });
  },







  //从upyun加载开通城市数据到本地
  GetOpenCity(app, f, fun) {
    var t = this;
    var city_url = app.globalData.OpenCity_url;
    var city_path = app.globalData.OpenCity_path;
    var city_path_expire = app.globalData.OpenCity_ExpirePath;
    wx.request({
      url: city_url,
      success(CityInfo) {
        if (/^Gets\({.*}\)$/.test(CityInfo.data)) {
          var CityInfo2 = app.TrimGets(CityInfo.data);
          f.Writes2(city_path, CityInfo2, function (city_stat) {
            if (city_stat == 'ok') {
              if (app.globalData.LoadingConsole) {
                app.C('CityOpenInfo_upyun');
              }
              var CityInfo3 = JSON.parse(CityInfo2);
              app.globalData.OpenCityObj = CityInfo3;
              fun('ok');
              f.Writes2(city_path_expire, new Date().getTime()+'',function (expire_stat) {
                if(expire_stat != 'ok'){
                  app.ViewError('10008 wirte OpenCityExpire to local file is fail', 161);
                  app.JumpError(10008);
                }
              });
            } else {
              app.ViewError('10010 write OpenCity to local file is fail', 161);
              app.JumpError(100010);
            }
          });
        } else {
          app.ViewError('10007 the OpenCity data format is error from upyun ', 161);
          app.JumpError(10007);
        }
      },
      fail() {
        app.ViewError('10006 get OpenCity from upyun is fail ', 161);
        app.JumpError(10006);
      }
    })
  },



//加载域名列表
GetDomainList(app, f, fun) {
  var t = this;
  var domain_url = app.globalData.DomainList_url;
  var domain_path = app.globalData.DomainList_path;
  var domain_path_expire = app.globalData.DomainList_ExpirePath;
  wx.request({
    url: domain_url,
    success(DomainInfo) {
      if (typeof DomainInfo.data == 'object' && DomainInfo.data.length > 0) {
        var DomainInfo2 = decodeURIComponent(JSON.stringify(DomainInfo.data));
        if (/^\["http:.*"\]$/.test(DomainInfo2)) {
          f.Writes2(domain_path, DomainInfo2,function (domain_stat) {
            if (domain_stat == 'ok') {
              if (app.globalData.LoadingConsole) {
                app.C('DomainList_upyun');
              }
              app.globalData.DomainListObj = JSON.parse(DomainInfo2);
              fun('ok');
              f.Writes2(domain_path_expire, new Date().getTime() + '', function (expire_stat) {
                if (expire_stat != 'ok') {
                  app.ViewError('10015 write DomainListExpire to local file is fail', 273);
                  app.JumpError(10015);
                }
              });
            } else {
              app.ViewError('10014 write DomainList to local file is fail', 273);
              app.JumpError(10014);
            }
          });
        } else {
          app.ViewError('10013 the DomainList data format is error from upyun', 273);
          app.JumpError(10013);
        }
      } else {
        app.ViewError('10012 the DomainList data format is error from upyun', 273);
        app.JumpError(10012);
      }
    },
    fail() {
      app.ViewError('10011 get DomainList from upyun is fail !',273);
      app.JumpError(10011);
    }
  })
},




  //加载商品分类数据
  GetGoodsType(app, f, fun) {
    var t = this;
    var goods_url = app.globalData.GoodsType_url;
    var goods_path = app.globalData.GoodsType_path;
    var goods_path_expire = app.globalData.GoodsType_ExpirePath;
    wx.request({
      url: goods_url,
      success(GoodsType) {
        if (/^Gets\(.*\)$/.test(GoodsType.data)) {
          var GoodsType2 = app.TrimGets(GoodsType.data);
          var GoodsTypeObj = t.GetGoodsType_parse(GoodsType2,app);
          if (GoodsTypeObj != 'err'){
            f.Writes2(goods_path, JSON.stringify(GoodsTypeObj),function(GoodsType_stat){
              if(GoodsType_stat == 'ok'){
                if (app.globalData.LoadingConsole) {
                  app.C('GoodsType_upyun');
                }
                app.globalData.GoodsTypeObj = GoodsTypeObj;
                fun('ok');
                f.Writes2(goods_path_expire, new Date().getTime() + '', function (expire_stat) {
                  if (expire_stat != 'ok') {
                    app.ViewError('10021 write GoodsTypeExpire to local file is fail', 273);
                    app.JumpError(10021);
                  }
                });
              }else{
                app.ViewError('10020 write GoodsType to local file is fail', 273);
                app.JumpError(10020);
              }
            });
          }else{
            app.ViewError('10019 parse GoodsType data is fail', 273);
            app.JumpError(10019);
          }
        } else {
          app.ViewError('10018 the GoodsType data format is error from upyun', 273);
          app.JumpError(10018);
        }
      },
      fail() {
        app.ViewError('10017 get GoodsType from upyun is fail !', 273);
        app.JumpError(10017);
      }
    })
  },

  GetGoodsType_parse(GoodsTypeStr,app){
    var t = this;
    if(/^\[.*\]$/.test(GoodsTypeStr)){
      var GoodsTypeList = JSON.parse(GoodsTypeStr);
      var g1 = [];
      var g2 = [];
      var g3 = [];
      for (var i = 0; i < GoodsTypeList.length; i++) {
        if (GoodsTypeList[i].level == 1) {
          g1.push(GoodsTypeList[i]);
        }
        if (GoodsTypeList[i].level == 2) {
          g2.push(GoodsTypeList[i]);
        }
        if (GoodsTypeList[i].level == 3) {
          g3.push(GoodsTypeList[i]);
        }
      }
      if(g3.length > 0){
        for (var j = 0; j < g2.length; j++) {
          var g3_arr = [];
          for (var k = 0; k < g3.length; k++) {
            if (g3[k].parent_id == g2[j].id) {
              g3_arr.push(g3[k]);
            }
          }
          g2[j].g3 = g3_arr;
        }
      }
      if(g2.length > 0){
        for (var i=0;i<g1.length;i++) {
          var g2_arr = [];
          for(var j=0;j<g2.length;j++){
            if(g1[i].id == g2[j].parent_id){
              g2_arr.push(g2[j]);
            }
          }
          g1[i].g2 = g2_arr;
        }
      }
      var GoodsType_obj = { "g1": g1};
      return GoodsType_obj
    }else{
      return 'err';
    }
  },



  //加载状态集合
  GetStatusSet(app, f, fun) {
    var status_url = app.globalData.StatusSet_url;
    var status_path = app.globalData.StatusSet_path;
    var status_path_expire = app.globalData.StatusSet_ExpirePath;
    var expire_long = app.globalData.StatusSet_ExpireLong;
    f.Has(status_path, function (h) {
      var file_stat = false;
      var upyun_stat = false;

      if (h != 'ok') {
        GetStatusSet_Upyun2(function (s) { if (s == 'ok') upyun_stat = true; })   //请求upyun
      }else{
        f.Reads(status_path, function (StatusSetRes) {
          if (/^{.*}$/.test(StatusSetRes)) {
            var StatusSetRes2 = JSON.parse(StatusSetRes);
            if (StatusSetRes2.data){
              if (app.globalData.LoadingConsole) app.C('statusSet_file ok'); 
              file_stat = true;
              app.globalData.StatusSetObj = StatusSetRes2.data;   //获取文件缓存的数据
              if (StatusSetRes2.expire + 5000 < new Date().getTime()){   //数据过期了
                GetStatusSet_Upyun2(function (s) { if (s == 'ok') upyun_stat = true; })   //数据过期，请求upyun
              }else{
                upyun_stat = true;
              }
            }else{
              GetStatusSet_Upyun2(function (s) { if (s == 'ok') upyun_stat = true; })   //文件对象数据异常，请求upyun
            }
          }else{
            GetStatusSet_Upyun2(function (s) { if (s == 'ok') upyun_stat = true; })   //文件字串数据格式异常，请求upyun
          }
        });
      }
      setTimeout(function () {
        if (!file_stat && !upyun_stat) {
          fun('err');
        } else {
          fun('ok');
        }
      }, 300);
    });

    function GetStatusSet_Upyun2(fun){
      GetStatusSet_Upyun(status_url, status_path, status_path_expire, app, f, function(stat){
        fun(stat);
      });
    }
    //upyun获取StatusSet状态集合数据
    function GetStatusSet_Upyun(status_url, status_path, status_path_expire, app, f, fun) {
      wx.request({
        url: status_url,
        success(StatusSet) {
          if (/^Gets\({.*}\)$/.test(StatusSet.data)) {
            var tmp = {};
            tmp.expire = new Date().getTime();
            tmp.data = JSON.parse(app.TrimGets(StatusSet.data));
            f.Writes2(status_path, JSON.stringify(tmp), function (status_stat) {
              if (status_stat == 'ok') {
                if (app.globalData.LoadingConsole) app.C('statusSet_upyun');
                app.globalData.StatusSetObj = tmp.data;
                fun('ok');
              } else {
                fun('err');
              }
            });
          } else {
            fun('err');
          }
        },
        fail() {
          fun('err');
        }
      })
    }
  },






/*
  ### 检测指定字段状态是否有效(是否有更新)  (全局)
  参一：object   文件操作类对象 
  参二：object   app 对象
  参三：int      要检测的类别  1：开通城市，2：域名列表， 3：商品分类列表
  参四：function 回调，返回参一ok为有效，err为失效，有更新了 ,err时会同时反加参二 ，其为字段状态缓存路径
  示例：
      t.CheckFieldStatusFail(f, app, 1, function (res) {  //检测
        if (res == 'ok') {
          console.log('OpenCity_file');
          OpenCityStat = true;
        }else{
          f.DelFile(app.globalData.OpenCity_path,'',function(){ //删除数据缓存文件
            t.GetOpenCity(app, f, function (s1) {  //重新加载
              if (s1 == 'ok') {
                OpenCityStat = true;
              }
            })
          });
        }
      });
*/
CheckFieldStatusFail(f, app, type, fun) {
  //var status_path = app.globalData.StatusSet_path;
  switch (type) {
    case 1: //OpenCity
      var field_path = app.globalData.OpenCity_ExpirePath;
      var FieldName = app.globalData.OpenCityName;
      break;
    case 2: //DomainList
      var field_path = app.globalData.DomainList_ExpirePath;
      var FieldName = app.globalData.DomainListName;
      break;
    case 3: //GoodsTypeList
      var field_path = app.globalData.GoodsType_ExpirePath;
      var FieldName = app.globalData.GoodsTypeName;
      break;
  }
  if(!app.globalData.StatusSetObj){
    app.ViewError('10005 get StatusSet from globalData is fail', 509);
    app.JumpError(10005);
    return;
  }
  var StatusSetObj = app.globalData.StatusSetObj;
  var check_stat = false;
  for (var i in StatusSetObj) {
    if (i == FieldName) {  //如果状态集合中包含指定字段
      check_stat = true;
      var StatusSetTime = parseInt(StatusSetObj[i]) * 1000;
      f.Has(field_path, function (s2) {  //如果有过期缓存
        if (s2 == 'ok') {  //进行比对
          f.Reads(field_path,function (VersionTime) {
            if (StatusSetTime >= parseInt(VersionTime)) { //过期
              if (app.globalData.LoadingConsole) {
                console.log(FieldName + '过期');
              }
              fun('err1');
            } else {
              fun('ok');
            }
          });
        } else { //没有过期缓存，说明滑数据需要加载
          fun('err2');
        }
      })
      break;
    }
  }
  if (!check_stat){
    fun("err3");
  }
}


})